﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Model.ParamModel;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using YiYiTong.Rocket.Model;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class OrderMasterController : BaseController
    {
        #region 获取列表
        [Description("销售订单列表")]
        [ViewPage]
        public ActionResult OrderMasterList(OrderMasterQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.Title = "销售订单列表";
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = getOrderMasterList(queryModel);

            var total_list = (from t in queryable
                              group t by 1 into g
                              select new
                              {
                                  total_money = g.Sum(t => t.total_money)
                              }).ToList();

            ViewData["total_money"] = total_list.Any() ? total_list[0].total_money : 0;

            int rowcounts = queryable.Count();
            ViewData["AllCount"] = rowcounts;

            var querylist = queryable.OrderByDescending(t => t.order_id)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();


            PagedList<View_Order> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_Order>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [NoVerify]
        public ActionResult downOrderMasterList(OrderMasterQueryModel queryModel)
        {
            queryModel.Trim();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = getOrderMasterList(queryModel);

            var querylist = queryable.OrderByDescending(t => t.order_id)
                .ToList();


            string strOutPut = string.Empty;
            string Excel = OrderMasterlistExcel(querylist, out strOutPut);
            ResponseMsg resMsg = new ResponseMsg();

            if (strOutPut != "导出成功")
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strOutPut;

                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            byte[] fileContents = Encoding.UTF8.GetBytes(Excel.ToString());
            return File(fileContents, "application/ms-excel", "orderlist_" + DateTime.Now.ToString(4) + ".xls");

        }

        public string OrderMasterlistExcel(List<View_Order> listmodel, out string strOutPut)
        {
            List<string> list_title = new List<string> {
                "订单号码",
                "会员账号",
                "型号",
                "数量",
                "单位",
                "币别",
                "是否含税",
                "订单金额",
                "退货金额",
                "退款状态",
                "供货价",
                "销售价",
                "佣金比例",
                "佣金额",
                "订单状态",
                "下单时间",
                "支付类型",
                "是否支付",
                "支付时间",
                "是否发货",
                "供货商名称",
                "供货商品类",
                "供货商负责人",
                "采购商负责人",
                "收货人",
                "收货地址",
                "联系电话"
            };
            ExportExcel Excel = new ExportExcel();
            DataTable dt = new DataTable();
            list_title.ForEach(t => dt.Columns.Add(t));
            dt.Columns["订单号码"].DataType = typeof(StringNumber);
            dt.Columns["会员账号"].DataType = typeof(StringNumber);
            dt.Columns["型号"].DataType = typeof(StringNumber);
            dt.Columns["供货商名称"].DataType = typeof(StringNumber);
            dt.Columns["供货商品类"].DataType = typeof(StringNumber);
            dt.Columns["供货商负责人"].DataType = typeof(StringNumber);
            dt.Columns["采购商负责人"].DataType = typeof(StringNumber);
            dt.Columns["收货人"].DataType = typeof(StringNumber);
            dt.Columns["收货地址"].DataType = typeof(StringNumber);
            dt.Columns["联系电话"].DataType = typeof(StringNumber);
            if (!listmodel.Any())
            {
                return Excel.DtToExcel(dt, list_title, out strOutPut);
            }

            var order_id_list = new List<long>();
            listmodel.ForEach(t =>
            {
                order_id_list.Add(t.order_id);
            });
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var refuse_order_list = dbcontext.ADZ_RefundOrder.Where(t => t.business_order_type < 2 && order_id_list.Contains(t.order_master_id.Value)).ToList();



            for (int i = 0; i < listmodel.Count; i++)
            {
                long order_id = listmodel[i].order_id;
                var goods = (
                from a in dbcontext.ADZ_OrderDetails.Where(details => details.order_id.Value == order_id)
                join b in dbcontext.ADZ_GoodsMaster on a.goods_id.Value equals b.goods_id
                join c in dbcontext.ADZ_SupplierMaster on b.supplier_id.Value equals c.supplier_id
                select new
                {
                    b.goods_id,
                    MPN = b.MPN,
                    a.amount,
                    b.goods_unit,
                    currency_type = b.currency_type,
                    b.include_tax, 
                    a.total_money,
                    b.supply_price,
                    base_price = a.price,
                    sell_price = a.sell_price,
                    b.commission_rate,
                    commission_money = (a.price - b.supply_price) * a.amount,
                    c.supplier_name,
                    c.contact_name,
                    c.manage_name,
                    c.supplier_type
                }
                ).ToList();

                List<ADZ_OrderDetails> refund_goods_list = new List<ADZ_OrderDetails>();
                var refund_order = refuse_order_list.FirstOrDefault(t => t.order_master_id == order_id);
                if (refund_order != null)
                {
                    refund_goods_list = JsonHelper.Deserialize<List<ADZ_OrderDetails>>(refund_order.refund_goods);

                }
                foreach (var item in goods)
                {
                    DataRow dr = dt.NewRow();
                    dr["订单号码"] = StringNumber.Crt(listmodel[i].order_NO);
                    dr["会员账号"] = StringNumber.Crt(listmodel[i].account_mobile);

                    dr["型号"] = StringNumber.Crt(item.MPN);
                    dr["数量"] = item.amount;
                    dr["单位"] = item.goods_unit;
                    dr["币别"] = MyEnumHelper.GetEnumItemDescription<CurrencyType>(item.currency_type);
                    dr["是否含税"] = MyEnumHelper.GetEnumItemDescription<include_tax>(item.include_tax);
                    dr["订单金额"] = item.total_money;
                    dr["退货金额"] = 0;
                    var ref_goods = refund_goods_list.FirstOrDefault(t => t.goods_id.Value == item.goods_id);
                    if (ref_goods != null)
                    {
                        dr["退货金额"] = ref_goods.total_money;
                        if (refund_order.status == 2)
                        {
                            dr["退款状态"] = "退款完成";
                        }
                        else
                        {
                            if (refund_order.tow_audit_status == 0)
                            {
                                dr["退款状态"] = " 等待复审";
                                if (refund_order.first_audit_status == 0)
                                {
                                    dr["退款状态"] = "等待初审";
                                }
                                else if (refund_order.first_audit_status == 1)
                                {
                                    dr["退款状态"] = "初审通过 等待复审";

                                }
                                else if (refund_order.first_audit_status == 2)
                                {
                                    dr["退款状态"] = "初审驳回";
                                }
                            }
                            else if (refund_order.tow_audit_status == 1)
                            {
                                dr["退款状态"] = " 复审通过";
                            }
                            else if (refund_order.tow_audit_status == 2)
                            {
                                dr["退款状态"] = " 复审驳回";
                            }


                        }
                    }
                    dr["供货价"] = item.supply_price;
                    dr["销售价"] = item.sell_price;
                    if (item.sell_price > 0)
                        dr["佣金比例"] = 1.00m * (item.sell_price - item.supply_price) / item.sell_price;
                    if (item.sell_price > 0)
                        dr["佣金额"] = 1.00m * (item.sell_price - item.supply_price) * item.amount;

                    dr["订单状态"] = MyEnumHelper.GetEnumItemDescription<OrderStatus>(listmodel[i].order_status);
                    dr["下单时间"] = listmodel[i].create_time.ToString(1);
                    dr["支付类型"] = MyEnumHelper.GetEnumItemDescription<PayType>(listmodel[i].pay_type);
                    dr["是否支付"] = listmodel[i].is_succ == 1 ? "已支付" : "未支付";
                    dr["支付时间"] = listmodel[i].pay_succ_time.ToString(1);
                    dr["是否发货"] = (MyEnumHelper.GetEnumItemDescription<IsSend>(listmodel[i].is_send.Value));

                    dr["供货商名称"] = StringNumber.Crt(item.supplier_name);
                    var suppliertype = dbcontext.ADZ_SupplierType.FirstOrDefault(t => t.supplier_type == item.supplier_type);
                    if (suppliertype != null)
                        dr["供货商品类"] = StringNumber.Crt(suppliertype.supplier_type_name);
                    dr["供货商负责人"] = StringNumber.Crt(item.contact_name);
                    dr["采购商负责人"] = StringNumber.Crt(item.manage_name);

                    dr["收货人"] = StringNumber.Crt(listmodel[i].receiver);
                    dr["联系电话"] = StringNumber.Crt(listmodel[i].receiver_telephone);//
                    dr["收货地址"] = StringNumber.Crt(listmodel[i].address_desc);

                    dt.Rows.Add(dr);
                }
            }

            return Excel.DtToExcel(dt, list_title, out strOutPut);
        }

        private IQueryable<View_Order> getOrderMasterList(OrderMasterQueryModel queryModel)
        {

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = dbcontext.View_Order.Where(t => t.is_del == 0);

            if (!string.IsNullOrEmpty(queryModel.mpn))
            {
                var goods_ids = from t in dbcontext.ADZ_GoodsMaster
                                where t.MPN.Contains(queryModel.mpn)
                                select t.goods_id;

                var order_ids = from t in dbcontext.ADZ_OrderDetails
                                where goods_ids.Contains(t.goods_id.Value)
                                select t.order_id;
                queryable = queryable.Where(t => order_ids.Contains(t.order_id));
            }

            if (!string.IsNullOrEmpty(queryModel.supplier_name))
            {
                var supplier_ids = from t in dbcontext.ADZ_SupplierMaster
                                   where t.supplier_name.Contains(queryModel.supplier_name)
                                   select t.supplier_id;

                var goods_ids = from t in dbcontext.ADZ_GoodsMaster
                                where supplier_ids.Contains(t.supplier_id.Value)
                                select t.goods_id;

                var order_ids = from t in dbcontext.ADZ_OrderDetails
                                where goods_ids.Contains(t.goods_id.Value)
                                select t.order_id;

                queryable = queryable.Where(t => order_ids.Contains(t.order_id));

            }



            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile.StartsWith(queryModel.account_mobile));

            if (!string.IsNullOrWhiteSpace(queryModel.order_NO))
                queryable = queryable.Where(t => t.order_NO.StartsWith(queryModel.order_NO));

            if (queryModel.order_source != -10)
                queryable = queryable.Where(t => t.order_source == queryModel.order_source);

            if (queryModel.order_status != -10)
            {
                if (queryModel.order_status == -6)
                {
                    queryable = queryable.Where(t => t.order_status != (int)OrderStatus.Cancel);
                }
                else
                {
                    queryable = queryable.Where(t => t.order_status == queryModel.order_status);
                }
            }

            if (queryModel.is_send != -10)
                queryable = queryable.Where(t => t.is_send == queryModel.is_send);

            if (queryModel.pay_type != -10)
            {
                if (queryModel.pay_type == 1)
                    queryable = queryable.Where(t => t.pay_type >= queryModel.pay_type);
                else
                    queryable = queryable.Where(t => t.pay_type == queryModel.pay_type);
            }
            if (queryModel.is_succ != -10)
                queryable = queryable.Where(t => t.is_succ == queryModel.is_succ);


            if (queryModel.create_time_begin != null)
                queryable = queryable.Where(t => t.create_time >= queryModel.create_time_begin);
            if (queryModel.create_time_end != null)
            {
                var endTime = queryModel.create_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < endTime);
            }


            if (queryModel.pay_succ_time_begin.HasValue)
                queryable = queryable.Where(t => t.pay_succ_time >= queryModel.pay_succ_time_begin);
            if (queryModel.pay_succ_time_end.HasValue)
            {
                var endTime = queryModel.pay_succ_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.pay_succ_time < endTime);
            }
            return queryable;
        }

        [Description("销售订单详情")]
        [ViewPage]
        public ActionResult OrderMasterInfo(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            OrderMasterModel paramModel = new OrderMasterModel();
            ViewBag.Title = "销售订单详情";
            if (id > 0)
            {
                paramModel.view_Order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == id);

                paramModel.aDZ_MemberMaster = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == paramModel.view_Order.uid);

                if (paramModel.view_Order.is_invoice.Value == 1)
                {
                    //发票信息
                    var aDZ_OrderInvoiceRel = dbcontext.ADZ_OrderInvoiceRel.FirstOrDefault(t => t.order_id == id);
                    if (aDZ_OrderInvoiceRel != null)
                    {
                        paramModel.aDZ_OrderInvoiceRel = aDZ_OrderInvoiceRel;
                    }
                }

                //收货信息
                paramModel.aDZ_OrderAddress = dbcontext.ADZ_OrderAddress.FirstOrDefault(t => t.order_id == id);
                paramModel.aDZ_OrderAddress = paramModel.aDZ_OrderAddress ?? new ADZ_OrderAddress();

                var express = dbcontext.ADZ_ExpressConfig.FirstOrDefault(t => t.express_com == paramModel.aDZ_OrderAddress.express_com);
                if (express != null)
                    paramModel.aDZ_OrderAddress.express_com = express.express_name;

                //商品列表
                var aDZ_OrderDetails = dbcontext.ADZ_OrderDetails.Where(t => t.order_id == id).ToList();
                foreach (var item in aDZ_OrderDetails)
                {
                    paramModel.orderGoods.Add(new OrderGoods()
                    {
                        views_Goods = dbcontext.Views_Goods.FirstOrDefault(t => t.goods_id == item.goods_id),
                        aDZ_OrderDetails = item
                    });
                }

            }

            return View(paramModel);
        }


        [Description("设置已开票")]
        [HttpPost]
        public ActionResult setInvoiced(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                if (order_master.is_succ.Value == (int)PaySucc.NotPay)
                {
                    resMsg.Message = "此订单还未支付，不能开票。";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }

            var entity = dbcontext.ADZ_OrderInvoiceRel.FirstOrDefault(t => t.order_id == id);
            if (entity != null)
            {
                if (entity.is_ready.Value == 1)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = "您之前已经开过发票了";

                }
                else
                {
                    entity.is_ready = 1;
                    entity.invoice_date = DateTime.Now;
                }
                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order_master.order_id,
                    opmsg = "标记为已开发票-管理后台",
                    op_user = new CurrentUser().user.loginName
                });
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("设置已支付")]
        [HttpPost]
        public ActionResult setpay(string img_url, long order_id = 0)
        {
            string pay_img_url = "";
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ///以下添加新图片
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            LogHelper.Debug("图片信息：" + hfc.Count);

            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    var file = hfc[i];
                    var putResult = ImageFileBiz.UpImg(file, "payimg");
                    if (!putResult.Item1)
                    {
                        resMsg.Message += (putResult.Item2);
                    }
                    else
                    {
                        pay_img_url = putResult.Item3;
                        LogHelper.Debug("图片上传成功：" + putResult.Item3);
                    }
                }
            }
            else
            {
                pay_img_url = img_url;
                if (string.IsNullOrEmpty(img_url))
                {
                    LogHelper.Debug("图片删除：");
                }
            }

            if (string.IsNullOrEmpty(pay_img_url))
            {
                resMsg.Message = "没有支付凭据不能设置已支付。";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == order_id);
            if (order_master != null)
            {
                order_master.is_confirm_payed = 1;
                order_master.pay_img_url = pay_img_url;
                dbcontext.SaveChanges();
                if (order_master.is_succ.Value == (int)PaySucc.Paid)
                {
                    resMsg.Message = "此订单已支付。";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                var payret = OrderBiz.Instance.OrderPaySucc(order_id, (int)PayType.UnderLine);
                if (payret)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = order_master.order_id,
                        opmsg = "上传凭证并设置为支付成功-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("关闭订单")]
        [HttpPost]
        public ActionResult cancelorder(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                string order_no = order_master.order_NO;
                var ret = OrderBiz.Instance.CancelOrder(order_no, 1);
                if (ret.Item1)
                {
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = order_master.order_id,
                        opmsg = "关闭订单-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
                else
                {
                    resMsg.Message = ret.Item2;
                }
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("设为已发货")]
        [HttpPost]
        public ActionResult setSended(long id, string express_NO, string express_com, byte is_send)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                string order_no = order_master.order_NO;
                if (order_master.is_send.Value > (int)IsSend.NotSend)
                {
                    resMsg.Message = "订单已发货";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                if (order_master.is_succ != 1)
                {
                    resMsg.Message = "支付成功的订单才能设为已发货";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                order_master.is_send = is_send;
                order_master.send_time = DateTime.Now;

                if (is_send == (byte)IsSend.Sended)
                {
                    var aDZ_OrderAddress = dbcontext.ADZ_OrderAddress.FirstOrDefault(t => t.order_id == id);
                    if (aDZ_OrderAddress != null)
                    {
                        if (!string.IsNullOrWhiteSpace(express_NO))
                        {
                            aDZ_OrderAddress.express_NO = express_NO.Trim();
                        }
                        var express = dbcontext.ADZ_ExpressConfig.FirstOrDefault(t => t.express_name == express_com);
                        if (express != null)
                            aDZ_OrderAddress.express_com = express.express_com.Trim();
                    }

                    dbcontext.SaveChanges();
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = id,
                        opmsg = $"订单开始发货-管理后台,快递公司：{express_com}，快递单号：{express_NO}",
                        op_user = new CurrentUser().user.loginName
                    });
                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "订单发货",
                            MsgText = $"您的订单{order_master.order_NO}已安排发货，收货地址：{aDZ_OrderAddress.address_desc}，请保持电话畅通。"
                        },
                        ReceiveUids = order_master.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);
                }
                if (is_send == (byte)IsSend.GetUseSelf)
                {
                    dbcontext.SaveChanges();
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";

                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = id,
                        opmsg = $"订单开始发货-管理后台,设置为自提取货",
                        op_user = new CurrentUser().user.loginName
                    });
                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "订单自提取货",
                            MsgText = $"您的订单{order_master.order_NO}已设置为自提取货，请及时处理。"
                        },
                        ReceiveUids = order_master.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);
                }
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("确认收货")]
        [HttpPost]
        public ActionResult confirmOrder(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                string order_no = order_master.order_NO;
                var ret = OrderBiz.Instance.ConfirmOrder(order_no);
                if (ret.Item1)
                {
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = id,
                        opmsg = "订单确认发货-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
                else
                {
                    resMsg.Message = ret.Item2;
                }
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("确认已支付")]
        [HttpPost]
        public ActionResult setConfirmpay(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                if (order_master.is_succ == 1)
                {
                    order_master.is_confirm_payed = 1;
                    dbcontext.SaveChanges();
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = id,
                        opmsg = "订单人工确认支付-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });
                }
                else
                {
                    resMsg.Message = "操作之前请确认订单已经支付成功";
                }

            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("编辑订单信息")]
        [HttpPost]
        public ActionResult doSave(View_Order order, string express_NO, string express_com)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == order.order_id);
            if (order_master != null)
            {
                order_master.remark = order.remark;

                var aDZ_OrderAddress = dbcontext.ADZ_OrderAddress.FirstOrDefault(t => t.order_id == order.order_id);
                if (aDZ_OrderAddress != null)
                {
                    aDZ_OrderAddress.receiver = order.receiver.Trim();
                    aDZ_OrderAddress.address_desc = order.address_desc.Trim();
                    aDZ_OrderAddress.receiver_telephone = order.receiver_telephone.Trim();
                }

                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order_master.order_id,
                    opmsg = "维护订单信息-管理后台",
                    op_user = new CurrentUser().user.loginName
                });
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        //设置快递信息

        //var express = dbcontext.ADZ_ExpressConfig.FirstOrDefault(t => t.express_name == express_com);
        //if (express != null)
        //    aDZ_OrderAddress.express_com = express.express_com.Trim();
        //aDZ_OrderAddress.express_NO = express_NO.Trim();


        [Description("修改订单价格")]
        [HttpPost]
        public ActionResult modifytotalmoney(long id = 0, decimal newtotalmoney = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";
            if (id <= 0 || newtotalmoney <= 0)
            {
                resMsg.Message = "提交参数错误，请确认价格和订单都是正确的。";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            var order_master = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == id);
            if (order_master != null)
            {
                var oldtotalmoney = order_master.total_money;
                if (order_master.order_status != (int)OrderStatus.WaitPay || order_master.is_succ == 1)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = "只有未支付的订单才能修改价格";
                }
                else
                {
                    order_master.total_money = newtotalmoney;
                    dbcontext.SaveChanges();
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = id,
                        opmsg = $"订单价格由{oldtotalmoney}改为{newtotalmoney}-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });
                    resMsg.IsSuccess = true;
                    resMsg.Message = "价格修改成功";

                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "订单价格调整",
                            MsgText = $"您的订单{order_master.order_NO}价格已调整为{newtotalmoney}，请尽快支付。"
                        },
                        ReceiveUids = order_master.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region
        [Description("改价详情")]
        [NoVerify]
        public ActionResult EditPrice(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            OrderMasterModel paramModel = new OrderMasterModel();
            if (id > 0)
            {
                paramModel.view_Order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == id);

                paramModel.aDZ_MemberMaster = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == paramModel.view_Order.uid);

                if (paramModel.view_Order.is_invoice.Value == 1)
                {
                    //发票信息
                    var aDZ_OrderInvoiceRel = dbcontext.ADZ_OrderInvoiceRel.FirstOrDefault(t => t.order_id == id);
                    if (aDZ_OrderInvoiceRel != null)
                    {
                        paramModel.aDZ_OrderInvoiceRel = aDZ_OrderInvoiceRel;
                    }
                }

                //商品列表
                var aDZ_OrderDetails = dbcontext.ADZ_OrderDetails.Where(t => t.order_id == id).ToList();
                foreach (var item in aDZ_OrderDetails)
                {
                    paramModel.orderGoods.Add(new OrderGoods()
                    {
                        views_Goods = dbcontext.Views_Goods.FirstOrDefault(t => t.goods_id == item.goods_id),
                        aDZ_OrderDetails = item
                    });
                }
            }
            return View(paramModel);
        }

        [Description("提交修改")]
        [HttpPost]
        public ActionResult DoEditPrice(EditPriceModel paramModel)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            foreach (var item in paramModel.aDZ_OrderDetails)
            {
                if (item.total_money < 0)
                {
                    resMsg.Message = "价格有问题，请检查再提交";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var ordermaster = dbcontext.ADZ_OrderMaster.FirstOrDefault(t => t.order_id == paramModel.order_id);
            if (ordermaster == null)
            {
                resMsg.Message = "请选择要修改价格的商品";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (ordermaster.order_source == 12)
            {
                resMsg.Message = "竞价订单不能修改单品价格";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            string loginfo = "";

            decimal new_total_money = 0m;
            paramModel.aDZ_OrderDetails.ForEach(t =>
            {
                new_total_money += t.total_money.Value;
                var orderdetail = dbcontext.ADZ_OrderDetails.FirstOrDefault(x => x.order_id == paramModel.order_id && x.goods_id == t.goods_id);
                if (orderdetail != null)
                {
                    var new_sell_price = Math.Round(t.total_money.Value / t.amount.Value, 6);
                    var goodinfo = dbcontext.ADZ_GoodsMaster.First(y => y.goods_id == orderdetail.goods_id);

                    if (new_sell_price != orderdetail.sell_price)
                    {
                        loginfo += $"物料{goodinfo.MPN}单价由{orderdetail.sell_price}改为{new_sell_price} \n\r";
                        orderdetail.sell_price = new_sell_price;
                    }
                    if (orderdetail.total_money != t.total_money)
                    {
                        loginfo += $"物料{goodinfo.MPN}总额由{orderdetail.total_money}改为{t.total_money} \n\r";
                        orderdetail.total_money = t.total_money;
                    }
                    if (orderdetail.amount != t.amount)
                    {
                        loginfo += $"物料{goodinfo.MPN}数量由{orderdetail.amount}改为{t.amount} \n\r";
                        orderdetail.amount = t.amount;
                    }
                }
            });
            if (!string.IsNullOrWhiteSpace(loginfo))
            {
                paramModel.reason = paramModel.reason ?? "";
                dbcontext.ADZ_OrderMasterLog.Add(new ADZ_OrderMasterLog
                {
                    create_time = DateTime.Now,
                    opmsg = paramModel.reason + $"订单价格由{ordermaster.total_money}调整为{new_total_money}：\n\r{loginfo}",
                    op_user = new CurrentUser().user.realName,
                    order_id = paramModel.order_id
                });
                ordermaster.total_money = new_total_money;
            }
            dbcontext.SaveChanges();
            resMsg.Message = "订单修改成功";
            resMsg.IsSuccess = true;
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 退款
        [Description("退款详情")]
        [NoVerify]
        public ActionResult RefundInfo(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            OrderMasterModel paramModel = new OrderMasterModel();
            if (id > 0)
            {
                paramModel.view_Order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == id);

                paramModel.aDZ_MemberMaster = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == paramModel.view_Order.uid);

                if (paramModel.view_Order.is_invoice.Value == 1)
                {
                    //发票信息
                    var aDZ_OrderInvoiceRel = dbcontext.ADZ_OrderInvoiceRel.FirstOrDefault(t => t.order_id == id);
                    if (aDZ_OrderInvoiceRel != null)
                    {
                        paramModel.aDZ_OrderInvoiceRel = aDZ_OrderInvoiceRel;
                    }
                }

                //商品列表
                var aDZ_OrderDetails = dbcontext.ADZ_OrderDetails.Where(t => t.order_id == id).ToList();
                foreach (var item in aDZ_OrderDetails)
                {
                    paramModel.orderGoods.Add(new OrderGoods()
                    {
                        views_Goods = dbcontext.Views_Goods.FirstOrDefault(t => t.goods_id == item.goods_id),
                        aDZ_OrderDetails = item
                    });
                }
            }
            return View(paramModel);
        }

        [Description("退款")]
        [HttpPost]
        public ActionResult Refund(long order_id, string good_ids, string moneys, string reason)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            if (string.IsNullOrEmpty(good_ids))
            {
                resMsg.Message = "请选择要退款的商品";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            if (string.IsNullOrEmpty(moneys))
            {
                resMsg.Message = "请输入要退款商品的订单总价";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            if (string.IsNullOrEmpty(reason))
            {
                resMsg.Message = "请输入退款原因";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            if (order_id > 0)
            {
                decimal refund_amt = 0;
                var g = StringHelper.Split(good_ids, ',');
                var m = StringHelper.Split(moneys, ',');

                List<ADZ_OrderDetails> refund_goods = new List<ADZ_OrderDetails>();
                for (int i = 0; i < g.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(g[i]))
                    {
                        var goods_id = long.Parse(g[i]);
                        var money = decimal.Parse(m[i]);
                        var order_details = dbcontext.ADZ_OrderDetails.FirstOrDefault(t => t.order_id == order_id && t.goods_id == goods_id);
                        if (money > order_details.total_money)
                        {
                            resMsg.Message = "退款金额不能大于商品订单总价";
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }

                        refund_amt += money;

                        //保存要退款的商品
                        order_details.total_money = money;
                        refund_goods.Add(order_details);

                    }
                }

                var order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == order_id);
                if (refund_amt > order.total_money)
                {
                    resMsg.Message = "退款金额不能大于订单总金额";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                string str_goods = JsonHelper.Serialize(refund_goods);
                string order_no = Utils.BuildOrderId("T");
                string apply_user = new CurrentUser().user.loginName;
                var result = OrderBiz.Instance.CreateRefundOrder(order_no, (int)BusinessOrderType.SaleOrder, order_id, refund_amt, str_goods, reason, apply_user, "");
                resMsg.IsSuccess = result.Item1;
                resMsg.Message = result.Item2;

                if (resMsg.IsSuccess)
                {
                    dbcontext.ADZ_OrderMasterLog.Add(new ADZ_OrderMasterLog
                    {
                        create_time = DateTime.Now,
                        opmsg = $"订单提交退款申请：{reason}，退款总金额：{refund_amt}",
                        op_user = new CurrentUser().user.realName,
                        order_id = order_id
                    });
                    dbcontext.SaveChanges();
                }

            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("初审列表")]
        [ViewPage]
        public ActionResult FirstRefundList(FirstRefundQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_RefundOrder.Where(t => 0 == 0);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile.StartsWith(queryModel.account_mobile));
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO.Contains(queryModel.replace_buyer_NO));
            if (!string.IsNullOrWhiteSpace(queryModel.master_order_no))
                queryable = queryable.Where(t => t.master_order_no.Contains(queryModel.master_order_no));
            if (!string.IsNullOrWhiteSpace(queryModel.order_no))
                queryable = queryable.Where(t => t.order_no.Contains(queryModel.order_no));
            if (queryModel.first_audit_status != -10)
                queryable = queryable.Where(t => t.first_audit_status == queryModel.first_audit_status);
            if (queryModel.business_order_type != -10)
            {
                //queryable = queryable.Where(t => t.business_order_type == queryModel.business_order_type);
            }
            if (queryModel.create_time_begin.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.create_time_begin);
            if (queryModel.create_time_end.HasValue)
            {
                var end_time = queryModel.create_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            decimal? refundAmt = queryable.Sum(t => t.refund_amt);
            ViewData.Add("AllAmt", refundAmt);
            var querylist = queryable.OrderByDescending(t => t.order_id).ThenByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_RefundOrder> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_RefundOrder>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("初审")]
        [HttpPost]
        public ActionResult FirstAudit(long order_id, int status, string msg)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var order = dbcontext.ADZ_RefundOrder.FirstOrDefault(t => t.order_id == order_id
            && t.status == (byte)RefundSatus.Apply && t.first_audit_status == (byte)AuditStatus.Create);
            if (order != null)
            {
                order.first_audit_time = DateTime.Now;
                order.first_audit_user = new CurrentUser().user.loginName;
                order.first_audit_status = (byte)status;
                order.first_audit_remark = msg;
                dbcontext.SaveChanges();

                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order.order_master_id,
                    opmsg = "订单退款初审完毕 " + MyEnumHelper.GetEnumItemDescription<AuditStatus>(status) + " " + msg,
                    op_user = new CurrentUser().user.loginName
                });
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);

        }

        [Description("复审列表")]
        [ViewPage]
        public ActionResult TowRefundList(FirstRefundQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_RefundOrder.Where(t => t.first_audit_status == 1);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile.StartsWith(queryModel.account_mobile));
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO.Contains(queryModel.replace_buyer_NO));
            if (!string.IsNullOrWhiteSpace(queryModel.master_order_no))
                queryable = queryable.Where(t => t.master_order_no.Contains(queryModel.master_order_no));
            if (!string.IsNullOrWhiteSpace(queryModel.order_no))
                queryable = queryable.Where(t => t.order_no.Contains(queryModel.order_no));
            if (queryModel.two_audit_status != -10)
                queryable = queryable.Where(t => t.tow_audit_status == queryModel.two_audit_status);
            if (queryModel.create_time_begin.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.create_time_begin);
            if (queryModel.create_time_end.HasValue)
            {
                var end_time = queryModel.create_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            decimal? refundAmt = queryable.Sum(t => t.refund_amt);
            ViewData.Add("AllAmt", refundAmt);
            var querylist = queryable.OrderByDescending(t => t.order_id).ThenByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_RefundOrder> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_RefundOrder>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("复审")]
        [HttpPost]
        public ActionResult TwoAudit(long order_id, int status, string msg)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var order = dbcontext.ADZ_RefundOrder.FirstOrDefault(t => t.order_id == order_id
            && t.first_audit_status == (byte)AuditStatus.AuditSucc);
            if (order != null)
            {
                order.tow_audit_time = DateTime.Now;
                order.tow_audit_user = new CurrentUser().user.loginName;
                order.tow_audit_status = (byte)status;
                order.two_audit_remark = msg;
                dbcontext.SaveChanges();

                /*  退款工作放给出纳了后面去了
                //todo 此处执行退款 20201121
                byte refund_status = (byte)RefundSatus.Fail;
                string refund_msg = string.Empty;
                //退款复审成功，开始线上退款
                if (status == (int)AuditStatus.AuditSucc)
                {
                    var result = OrderBiz.Instance.RefundOrder((int)BusinessOrderType.SaleOrder, (long)order.order_master_id, order.order_no, (decimal)order.refund_amt);
                    if (result.Item1)
                        refund_status = (byte)RefundSatus.Succ;
                    else
                        refund_msg = result.Item2;
                }
                order.status = refund_status;
                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功!" + refund_msg;
                */

                OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                {
                    order_id = order.order_master_id,
                    opmsg = "订单退款复审完毕 " + MyEnumHelper.GetEnumItemDescription<AuditStatus>(status) + " " + msg,
                    op_user = new CurrentUser().user.loginName
                });
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("退款详情")]
        [ViewPage]
        public ActionResult RefundOrderInfo(long id)
        {
            RefundOrderModel model = new RefundOrderModel();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (id > 0)
            {
                var refund_order = dbcontext.ADZ_RefundOrder.FirstOrDefault(t => t.order_id == id);
                if (refund_order != null)
                {
                    model.refundorder = refund_order;

                    if (refund_order.order_master_id > 0)
                    {
                        var view_order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == refund_order.order_master_id);
                        if (refund_order != null)
                            model.view_order = view_order;
                    }

                    //商品列表
                    var aDZ_OrderDetails = dbcontext.ADZ_OrderDetails.Where(t => t.order_id == refund_order.order_master_id).ToList();
                    foreach (var item in aDZ_OrderDetails)
                    {
                        model.orderGoods.Add(new OrderGoods()
                        {
                            views_Goods = dbcontext.Views_Goods.FirstOrDefault(t => t.goods_id == item.goods_id),
                            aDZ_OrderDetails = item
                        });
                    }
                }

            }
            return View(model);
        }
        #endregion

        #region 出纳退款列表
        [Description("出纳退款列表")]
        [ViewPage]
        public ActionResult RefundList(RefundQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_RefundOrder.Where(t => t.first_audit_status == 1 && t.tow_audit_status == 1);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile.StartsWith(queryModel.account_mobile));
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO.Contains(queryModel.replace_buyer_NO));
            if (!string.IsNullOrWhiteSpace(queryModel.master_order_no))
                queryable = queryable.Where(t => t.master_order_no.Contains(queryModel.master_order_no));
            if (!string.IsNullOrWhiteSpace(queryModel.order_no))
                queryable = queryable.Where(t => t.order_no.Contains(queryModel.order_no));
            if (queryModel.status != -10)
                queryable = queryable.Where(t => t.status == queryModel.status);
            if (queryModel.create_time_begin.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.create_time_begin);
            if (queryModel.create_time_end.HasValue)
            {
                var end_time = queryModel.create_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            decimal? refundAmt = queryable.Sum(t => t.refund_amt);
            ViewData.Add("AllAmt", refundAmt);
            var querylist = queryable.OrderByDescending(t => t.order_id).ThenByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_RefundOrder> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_RefundOrder>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [HttpPost]
        public ActionResult Tranfer(long orderId, string backroad, string transfer_remark)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            if (orderId <= 0)
            {
                resMsg.Message = "参数错误";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(backroad))
            {
                resMsg.Message = "请选择退款方式";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(transfer_remark))
            {
                resMsg.Message = "请填写备注信息";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            var refundOrder = dbcontext.ADZ_RefundOrder.FirstOrDefault(t => t.order_id == orderId);
            if (refundOrder == null)
            {
                resMsg.Message = "退款订单不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if(refundOrder.status == 2)
            {
                resMsg.Message = "退款已完成退款，无需再次操作";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            long uid = 0;
            byte pay_type = 0;
            string order_no = "";
            var order_master = dbcontext.View_Order.FirstOrDefault(t => t.order_id == refundOrder.order_master_id && t.is_succ == 1 && t.is_del == 0);
            if (order_master != null)
            {
                uid = order_master.uid.Value;
                pay_type = order_master.pay_type.Value;
                order_no = order_master.order_NO;
            }
            else
            {
                resMsg.Message = "退款订单不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }


            switch (backroad)
            {
                case "2"://退回到余额
                    string refund_name = "销售订单退款";
                    var chargeMember = dbcontext.ADZ_ChargeMaster.FirstOrDefault(t => t.uid == uid);
                    if (chargeMember != null)
                    {
                        //记录资金流水
                        bool addlog = AccountBiz.Instance.AddAmountLog((long)uid, refundOrder.refund_amt.Value, (int)OrderType.OrderMasterRefund, order_no, 0, refund_name, refund_name, 0);
                        if(!addlog)
                        {
                            resMsg.Message = "退回到余额失败，请检查是否多次退款";
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }
                        //加钱
                        chargeMember.charge_balance += refundOrder.refund_amt.Value;
                        chargeMember.account_balance += refundOrder.refund_amt.Value;
                        dbcontext.SaveChanges();


                        resMsg.IsSuccess = true;
                        resMsg.Message = " 退款到余额成功 ";
                        refundOrder.status = 2;
                        refundOrder.transfer_remark = transfer_remark + resMsg.Message + DateTime.Now.ToString(1);
                        refundOrder.is_tranfer = 1;
                        dbcontext.SaveChanges();
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                    resMsg.Message = "退回到余额失败";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                    
                    break;
                case "3"://支付宝原路退回
                    if(pay_type == (int)PayType.Alipay)
                    {
                        int business_order_type = (int)BusinessOrderType.SaleOrder;
                        var charge_order_alpay = dbcontext.ADZ_ChargeOrder.FirstOrDefault(t => t.order_master_id == refundOrder.order_master_id && t.uid == uid && t.business_order_type == business_order_type);
                        if (charge_order_alpay == null)
                        {
                            resMsg.Message = "支付宝原路退回失败：未找到支付宝订单信息";
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }
                        var result = AlipayBiz.Refund(charge_order_alpay.billno, refundOrder.refund_amt.Value);
                        if (!result.Item1)
                        {
                            resMsg.Message = "支付宝原路退回失败："+ result.Item2;
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }
                        resMsg.IsSuccess = true;
                        resMsg.Message = " 支付宝原路退回成功 ";
                        refundOrder.status = 2;
                        refundOrder.transfer_remark = transfer_remark + resMsg.Message + DateTime.Now.ToString(1);
                        refundOrder.is_tranfer = 1;
                        dbcontext.SaveChanges();
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }else
                    {
                        resMsg.Message = "订单不是支付宝支付，不能退到支付宝";
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                    break;
                case "4"://微信原路退还
                    if (pay_type == (int)PayType.Wechat)
                    {
                        int business_order_type = (int)BusinessOrderType.SaleOrder;
                        var charge_order = dbcontext.ADZ_ChargeOrder.FirstOrDefault(t => t.order_master_id == refundOrder.order_master_id && t.uid == uid && t.business_order_type == business_order_type);
                        if (charge_order == null)
                        {
                            resMsg.Message = "微信原路退回失败：未找到微信订单信息";
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }
                        string bill_no = charge_order.billno;
                        decimal amt = (decimal)charge_order.order_amt;
                        var result2 = WechatBiz.Refund(refundOrder.order_no, bill_no, amt, refundOrder.refund_amt.Value);
                        if (!result2.Item1)
                        {
                            resMsg.Message = "微信原路退回失败：" + result2.Item2;
                            return Json(resMsg, JsonRequestBehavior.AllowGet);
                        }
                        resMsg.IsSuccess = true;
                        resMsg.Message = " 微信原路退回成功 ";
                        refundOrder.status = 2;
                        refundOrder.transfer_remark = transfer_remark + resMsg.Message + DateTime.Now.ToString(1);
                        refundOrder.is_tranfer = 1;
                        dbcontext.SaveChanges();
                        return Json(resMsg, JsonRequestBehavior.AllowGet);                        
                    }
                    else
                    {
                        resMsg.Message = "订单不是微信支付，不能退到微信";
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                    break;
                case "0":
                    resMsg.IsSuccess = true;
                    resMsg.Message = " 线下退款标记成功 ";
                    refundOrder.status = 2;
                    refundOrder.transfer_remark = transfer_remark + resMsg.Message + DateTime.Now.ToString(1);
                    refundOrder.is_tranfer = 1;
                    dbcontext.SaveChanges();
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                    break;
            }

            
            dbcontext.SaveChanges();

            resMsg.IsSuccess = true;
            resMsg.Message = "操作成功!";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        #endregion
    }
}